import {
  Component,
  OnInit,
  Injector,
  ComponentRef,
  ChangeDetectorRef,
  ApplicationRef,
  EmbeddedViewRef,
  ComponentFactoryResolver
} from '@angular/core';
import { AlertComponent } from '../../alert/alert.component';
import HeroService from '@services/hero.service';
import { Hero, HeroArg } from '@configs/types';


@Component({
  selector: 'app-heros',
  templateUrl: './heros.component.html',
  styleUrls: ['./heros.component.css'],
  providers: [HeroService]
})
export class HerosComponent implements OnInit {
  // showUnless = false;
  showSpin = false;
  heroes: Hero[] = [];
  searchParams: HeroArg = {
    name: '',
    job: '',
    sort: 'desc'
  };
  private container: AlertComponent;
  private componentRef: ComponentRef<AlertComponent>;
  constructor(
    private cfr: ComponentFactoryResolver,
    private inject: Injector,
    private appRef: ApplicationRef,
    private heroServe: HeroService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.getHeroList();
  }
  getHeroList() {
    this.showSpin = true;
    this.heroServe.getHeroes(this.searchParams).subscribe((res: Hero[]) => {
      this.heroes = res;
      this.showSpin = false;
      this.cdr.markForCheck();
    });
  }
  search(): void {
    this.getHeroList();
  }
  reset(): void {
    this.searchParams = {
      name: '',
      job: '',
      sort: 'desc'
    };
    this.getHeroList();
  }
  showAlert(): void {
    if (!this.container) {
      this.container = this.getContainer();
    }
    this.container.setOptions({
      content: 'success-tip',
      theme: 'success'
    });
  }

  private getContainer(): AlertComponent {
    // 创建指定类型的组件工厂（生产指定类型组件）
    const factory = this.cfr.resolveComponentFactory<AlertComponent>(AlertComponent);
    // 根据组件类型，创建组件实例
    this.componentRef = factory.create(this.inject);
    // 将组件视图添加到视图树中，以激活变更检测
    this.appRef.attachView(this.componentRef.hostView);
    // 将组件添加到模板（包括app-alert标签），放到指定标签（如body）最后
    // document.body.appendChild((this.componentRef.location.nativeElement));
    document.body.appendChild((this.componentRef.hostView as EmbeddedViewRef<{}>).rootNodes[0] as HTMLElement);
    this.componentRef.onDestroy(() => {
      console.log('alert-component has been destroyed');
    });
    const { instance } = this.componentRef;
    instance.closeAlert.subscribe(() => {
      this.componentRef.destroy();
      this.container = null;
    });
    return instance;
  }
}
